package com.ming_za.odupdaterserver.core.mco_core.Cmd;

import com.ming_za.odupdaterserver.core.mco_core.API.CmdOperate;
import com.ming_za.odupdaterserver.core.utils.Msg;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 命令管理器，负责管理注册的所有命令，以及执行
 */
@Component
public class CmdManager implements BeanPostProcessor{

    @Getter
    private final Map<String,CmdData> cmdList = new HashMap<>();
    private final Thread cmdThread;
    @Getter
    private static CmdManager instance;
    public Scanner sc = new Scanner(System.in);

    public CmdManager() {
        instance = this;
        cmdThread = new Thread(()->{

            while (!Thread.currentThread().isInterrupted()){
                executeCommand(sc.nextLine());
            }

        },"Cmd-Thread");
        cmdThread.setDaemon(true);
        cmdThread.start();
    }

    /**
     * 执行指令
     * @param cmd 指令
     * @return 布尔值
     */
    public boolean executeCommand(String cmd) {

        if (cmd.isEmpty()){
            return false;
        }

        String[] args;

        if (cmd.contains(" ")){
            args = cmd.split(" ");
        }else {
            args = new String[]{cmd};
        }

        CmdData cmdData = cmdList.get(args[0]);
        if (cmdData != null){

            return cmdData.getCmdOperate().onCommand(cmd,args);
        }else {
            Msg.getInstance().soutMsg("&c未知指令！请输入&bhelp&a查看指令帮助");
        }

        return false;
    }

    /**
     * 注册指令
     */
    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        CmdCreate cmdCreate = bean.getClass().getDeclaredAnnotation(CmdCreate.class);
        if (cmdCreate == null){
            return bean;
        }
        if (bean instanceof CmdOperate cmdOperate){
            if (cmdList.containsKey(cmdCreate.cmd())){
                Msg.getInstance().error("&c指令注册失败！内存中已存在&6" + cmdCreate.cmd() + "&c相似命令");
                return bean;
            }
            cmdList.put(cmdCreate.cmd(),new CmdData(cmdCreate.explain().isEmpty() ? "" : " - " + cmdCreate.explain(),cmdOperate,cmdCreate.hide()));
            cmdOperate.onRegister();
        }else {
            Msg.getInstance().error("&c指令注册失败！" + bean + "未实现CmdOperate接口");
        }

        return bean;
    }
}
